package com.lanyou.cook.entitylistener.domain;

import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;

import org.apache.commons.lang3.StringUtils;
import org.pentaho.di.core.encryption.Encr;
import org.pentaho.di.core.encryption.KettleTwoWayPasswordEncoder;

import com.lanyou.cook.datadictionary.UserEnableType;
import com.lanyou.cook.entity.domain.userManagement.User;
import com.lanyou.cook.entity.kettle.KettleUser;

public class UserEntityListenerForKettleObject {

	// 保存和更新前，联动地更新R_DIRECTORY的信息
	
	@PrePersist
	public void prePersist(User target) {
		setKettleUser(target);
	}
	
	@PreUpdate
	public void preUpdate(User target) {
		setKettleUser(target);
	}
	
	private static void setPassword(User target){
		// 以Kettle的算法对密码进行加密
		String originalPassword = target.getPassword();
		if(StringUtils.isEmpty(originalPassword))
			throw new RuntimeException("Password is invalid");
		
		// 原密码未经过加密，则此时加密
		if(!originalPassword.startsWith(KettleTwoWayPasswordEncoder.PASSWORD_ENCRYPTED_PREFIX)){
			String encryptedPassword = Encr.encryptPasswordIfNotUsingVariables(target.getPassword());
			target.setPassword(encryptedPassword);
		}
	}
	
	public static void setKettleUser(User target){
		setPassword(target);
		
		boolean enable = (target.getRole() != null) && (UserEnableType.Enable.ValueCode.equals(target.getLoginStatus()));
		if(!enable){
			// 若不启用，则删除原Kettle用户
			target.setKettleUser(null);
		} else {
			KettleUser kettleUser = target.getKettleUser();
			if (kettleUser == null) {
				kettleUser = new KettleUser();
				target.setKettleUser(kettleUser);
			}
			
			kettleUser.setLogin(target.getUserCode());
			kettleUser.setName(target.getUserName());
			kettleUser.setPassword(target.getPassword());
			kettleUser.setDescription(target.getRemark());
		}
	}
	
}
